package com.example.springcloud.filter;

import com.example.springcloud.common.entity.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入 loginFilter");
        ServerHttpRequest request = exchange.getRequest();
        String authorization = request.getHeaders().getFirst("Authorization");
        if (authorization == null) {
            DataBuffer dataBuffer = getDataBuffer(exchange);
            return exchange.getResponse().writeWith(Flux.just(dataBuffer));
        }
        log.info("离开 loginFilter, 并放行");
        return chain.filter(exchange);
    }

    private DataBuffer getDataBuffer(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        ResponseResult<String> result = new ResponseResult<>(401, "no Authorization", "先登录");
        //定义字节数组
        byte[] data = null;
        //序列化JSON
        try {
            data = new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //封装成Data缓冲
        DataBuffer dataBuffer = response.bufferFactory().wrap(data == null ? new byte[0] : data);
        //设置JSON响应头，否则中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
        return dataBuffer;
    }
}
